package com.example.springboot_01_helloworld.controller;

import com.example.springboot_01_helloworld.model.Person;
import com.example.springboot_01_helloworld.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
public class UserController {

    @RequestMapping(value="/getUser", method= RequestMethod.GET)
    public User getUser() {
        User user=new User();
        user.setName("小明");
        user.setAge(12);
        user.setPass("123456");
        return user;
    }

    @RequestMapping(value="/getUser2", method= RequestMethod.GET)
    public User getUser2(String name) {
        User user=new User();
        user.setName(name);
        user.setAge(12);
        user.setPass("123456");
        return user;
    }

    @RequestMapping(value="/getUser3", method= RequestMethod.GET)
    public User getUser3(User user) {

        return user;
    }

    @RequestMapping(value="/getUser4/{name}", method= RequestMethod.GET)
    public User getUser4(@PathVariable String name) {
        User user=new User();
        user.setName(name);
        user.setAge(12);
        user.setPass("123456");
        return user;
    }

    //@Valid 参数前面添加 @Valid 注解，代表此对象使用了参数校验
    @RequestMapping(value="/saveUser",method= RequestMethod.POST)
    public String saveUser(@Valid User user, BindingResult result) {
        System.out.println("user:"+user);
        if(result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                System.out.println(error.getCode()+ "-" + error.getDefaultMessage());
            }
        }
        return "ok";

    }
    @Autowired
    private Person person;
    @RequestMapping("/testPerson")
    public Person testPerson(){
        return person;
    }

}
